package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动实例化与当前ReflectDemo8在同一个包下所有被@AutoRunClass标注的类
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                ReflectDemo8.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName(
                    ReflectDemo8.class.getPackage().getName() + "." + className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                System.out.println("实例化:" + className);
                Object o = cls.newInstance();
                System.out.println(o);
                //自动调用那些被@AutoRunMethod标注的方法
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods){
                    if(method.isAnnotationPresent(AutoRunMethod.class)){
                        //通过方法对象获取在该方法上使用的注解@AutoRunMethod
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        //通过注解对象获取传给value参数的值
                        int num = arm.value();
                        System.out.println("自动调用方法:"+method.getName()+":"+num+"次");
                        for(int i=1;i<=num;i++) {
                            method.invoke(o);
                        }
                    }
                }

            }
        }
    }
}
